import { useSnippetsStore } from '@renderer/stores'

export function useSearchSnippets () {
  const setSnippets = useSnippetsStore(state => state.setSnippets)

  const searchSnippets = async (keyword: string) => {
    let snippets: ISnippet[] = await window.api.sql(
      'select * from contents where title like @keyword or content like @keyword',
      'findAll',
      {
        keyword: `%${keyword}%`,
      },
    )
    const categories: ICategory[] = await window.api.sql(
      'select * from categories',
      'findAll',
    )
    snippets = snippets.map(s => ({
      ...s,
      categoryName: categories.find(c => c.id === s.category_id)?.name,
    }))
    setSnippets(snippets)
  }

  return {
    searchSnippets,
  }
}
